package io.github.lee.jel.ui.list

import android.app.Application
import com.chad.library.adapter4.BaseQuickAdapter
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseRefreshViewModel
import io.github.lee.core.vm.err.DataParseFailedException
import io.github.lee.core.vm.err.ViewModelException
import io.github.lee.repository.jel.data.session
import io.github.lee.repository.jel.domain.Item
import io.github.lee.repository.jel.repo.ItemRepository
import javax.inject.Inject
import kotlin.math.atan

@HiltViewModel
class ItemListVM @Inject constructor(
    application: Application,
    private val repo: ItemRepository
) : BaseRefreshViewModel<Item>(application) {

    var parentItem: Item? = null

    override fun onCreateAdapter(): BaseQuickAdapter<Item, *> =
        ItemListAdapter()

    //===Desc:=============================================================

    override fun onRefreshOrLoadMore(isRefresh: Boolean) {
        super.onRefreshOrLoadMore(isRefresh)
        
        if (isRefresh) {
            currentPage = 1
        } else {
            currentPage++
        }
        launchResult(
            block = {
                val userId = mContext.session?.userId
                val includeItemTypes = when (parentItem?.collectionType) {
                    "movies" -> listOf("Movie")
                    "tvshows" -> listOf("Series")
                    else -> null
                }
                repo.userItems(
                    userId, parentItem?.id,
                    page = currentPage,
                    includeItemTypes = includeItemTypes
                )
            },
            error = { error(it) }
        ) {
            if (!it.isSuccess) {
                if (isRefresh) {
                    error(ViewModelException(it.code, it.msg))
                } else {
                    loadMoreFail(DataParseFailedException(mContext))
                }
                return@launchResult
            }
            val data = it.data
            if (null == data) {
                if (isRefresh) {
                    error(DataParseFailedException(mContext))
                    refreshSuccess(false)
                } else {
                    loadMoreFail(DataParseFailedException(mContext))
                }
                return@launchResult
            }
            val items = data.items
            if (items.isNullOrEmpty()) {
                if (isRefresh) {
                    empty()
                    refreshSuccess(false)
                } else {
                    loadMoreSuccess(false)
                }
                return@launchResult
            }

            if (isRefresh) {
                submitList(items)
                refreshSuccess(true)
            } else {
                addAll(items)
                loadMoreSuccess(true)
            }

        }

    }

}